﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;
using System.Windows.Threading;
using System.Net;
using FSLib.IPMessager;
using FSLib.IPMessager.Entity;
using Table = FCNS.Data.Table;
using System.Net.NetworkInformation;

namespace DoubleH.Utility.Net
{
    public class NetUtility
    {
        /// <summary>
        /// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令),true表示Ping成功,false表示Ping失败 
        /// </summary>
        /// <param name="strIpOrDName">输入参数,表示IP地址或域名</param>
        /// <returns></returns>
        public static bool PingIpOrDomainName(string ipOrName, int timeOut = 5)
        {
            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = timeOut;
                PingReply objPinReply = objPingSender.Send(ipOrName, intTimeout, buffer, objPinOptions);
                string strInfo = objPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 获取指定ip的所在地址段的广播地址
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="subnetMask"></param>
        /// <returns></returns>
        public static IPAddress GetBroadcast(string ipAddress, string subnetMask)
        {
            try
            {
                byte[] ip = IPAddress.Parse(ipAddress).GetAddressBytes();
                byte[] sub = IPAddress.Parse(subnetMask).GetAddressBytes();

                // 广播地址=子网按位求反 再 或IP地址 
                for (int i = 0; i < ip.Length; i++)
                    ip[i] = (byte)((~sub[i]) | ip[i]);

                return new IPAddress(ip);
            }
            catch { return null; }
        }

        static IPMClient lanClient = null;
        public static IPMClient LanClient
        {
            get { return lanClient; }
        }

        static Host serverHost = null;
        public static Host ServerHost
        {
            get { return serverHost; }
        }

        /// <summary>
        /// 用户登录后，必须调用它启用网络连接
        /// </summary>
        public static void StartNet()
        {
            if (lanClient != null && lanClient.IsInitialized)
            {
                //如果已经登录了只是注销状态
                lanClient.Config.NickName = Table.UserS.LoginUser.Name;
                lanClient.Config.GroupName = Table.UserS.LoginUser._GroupSName;
                lanClient.Online();
            }
            else
            {
                lanClient = new FSLib.IPMessager.IPMClient(DoubleHConfig.AppConfig.ServerPort, Table.UserS.LoginUser.Name, Table.UserS.LoginUser._GroupSName, IPAddress.Any);
                if (lanClient.IsInitialized)
                {
                    lanClient.OnlineHost.HostOnline += (ss, ee) => OnlineHost(ee);
                    lanClient.Online();
                }
            }
        }
        /// <summary>
        /// 软件关闭前，必须调用它释放资源
        /// </summary>
        public static void CloseNet()
        {
            lanClient.OffLine();
            lanClient.Dispose();
            lanClient = null;
        }

        private static void OnlineHost(FSLib.IPMessager.Entity.OnlineHost.HostEventArgs e)
        {
            if (serverHost == null && e.Host.HostSub.Ipv4Address.Address.ToString() == DoubleHConfig.AppConfig.ServerIP)
                serverHost = e.Host;
        }

        public static bool SaveFileToServer(string fullFileName, string remoteDirectoryName, string remoteFileName)
        {
            if (serverHost == null)
                return SaveFileToLocal(fullFileName, remoteDirectoryName, remoteFileName);

            MessageBox.Show(File.Exists(fullFileName).ToString() + " " + lanClient.IsInitialized.ToString());
            if (!File.Exists(fullFileName) || !lanClient.IsInitialized)
                return false;

            MessageBox.Show(fullFileName + " " + remoteDirectoryName + " " + remoteFileName);
            FileTaskItem file = new FileTaskItem();
            file.FullPath = fullFileName;
            file.CurrentName = remoteDirectoryName;
            lanClient.PerformSendFile(new FileTaskItem[] { file }, string.Empty, false, false, serverHost);
            return true;
        }

        public static bool RemoveFileOnServer(string remoteFullFileName)
        {
            if (serverHost == null)
                return RemoveFileOnLocal(remoteFullFileName);

            return false;
        }

        public static string[] GetFileFromServer(string remoteDirectoryName)
        {
           return Directory.GetFiles(DbDefine.UploadFilePath + remoteDirectoryName);
        }

        private static bool RemoveFileOnLocal(string remoteFullFileName)
        {
            try
            {
                File.Delete(remoteFullFileName);
                return true;
            }
            catch   { return false; }//如果删除的是本机文件，这里会异常
        }

        private static bool SaveFileToLocal(string fullFileName, string remoteDirectoryName, string remoteFileName)
        {
            try
            {
                string dir = DbDefine.UploadFilePath + remoteDirectoryName + "\\";
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                File.Copy(fullFileName, dir + remoteFileName, true);
                return true;
            }
            catch { return false; }
        }
    }
}